package com.lost.octopus.es.processor.config.es.wrapper;

import com.lost.octopus.es.helper.entity.model.FieldConfig;
import com.lost.octopus.es.helper.entity.wrapper.AbstractQueryWrapper;
import com.lost.octopus.es.helper.entity.wrapper.EsQueryMultiplyKeyWrapper;
import com.lost.octopus.es.helper.util.ArrayUtil;

import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

import javax.annotation.Resource;

import lombok.extern.log4j.Log4j2;

/**
 * 多属性，多值或查询
 *
 * @author luo.hh
 * @date 2022/9/14 11:04
 */
@Log4j2
@Component
public class EsQueryMultiplyKeyValueWrapper extends AbstractQueryWrapper {
    @Resource
    private EsQueryMultiplyKeyWrapper esQueryMultiplyKeyWrapper;

    @Override
    public QueryBuilder addWrapper(BoolQueryBuilder boolQueryBuilder, FieldConfig field) {

        // 校验是数组后，直接用工具转换
        List<Object> values = ArrayUtil.transList(field.getValue());
        // 设置真实的查询条件
        if (CollectionUtils.isEmpty(values)) {
            return null;
        }
        BoolQueryBuilder query = QueryBuilders.boolQuery();
        values.forEach(o -> {
            FieldConfig copy = field.copy();
            copy.setValue(o);
            QueryBuilder queryBuilder = esQueryMultiplyKeyWrapper.useWrapper(copy);
            query.should(queryBuilder);
        });
        boolQueryBuilder.must(query);
        // 复用多值查询
        return query;
    }
}
